<template>
  <div>
    <el-dialog ref="dialog" :title="setTitle" :visible.sync="showDialog" width="50%" @close="closeDialog"  :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form @submit.native.prevent ref="form" :model="form" :rules="rules" size="small" label-position="right" label-width="110px" v-loading="init">
        <el-form-item :label="$root.lang.control.app.create.appName" prop="appName">
          <el-input v-model="form.appName"></el-input>
        </el-form-item>
        <el-form-item :label="$root.lang.control.app.create.appVersion" prop="appVersion">
          <el-input v-model="form.appVersion"></el-input>
        </el-form-item>
        <el-form-item :label="$root.lang.control.app.create.file" prop="appUrl">
          <el-input ref="fileInput" readonly v-model="form.showUrl" @blur="changeFile('appUrl')"></el-input>
          <el-upload
            ref="appUrl"
            class="upload-demo"
            :action="$root.fileUpload"
            enctype="multipart/form-data"
            :headers=headers
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="onsuccess"
            :before-upload="beforeUpload"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            accept=".jar"
            :file-list="fileList">
            <el-button size="small" type="primary" style="margin-top: 10px;display: block;">{{ $root.lang.control.app.create.selectFile }}</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传文件，且不超过kb</div> -->
          </el-upload>
        </el-form-item>
        <el-form-item :label="$root.lang.control.app.create.deviceType" prop="deviceType">
          <el-select v-model="form.deviceType" :placeholder="$root.lang.control.device.create.select">
            <el-option :label="item.typeName" :value="item.typeCode" :key="item.typeCode" v-for="item in deviceTypeList"></el-option>          
          </el-select>
        </el-form-item>
        <!-- <el-form-item :label="$root.lang.control.app.create.isPublic" prop="isPublic">
          <el-radio-group v-model="form.isPublic">
            <el-radio :label="item.value" :key="index" :value="item.value" v-for="(item, index) in baseState.isPublic" >{{ item.title}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item :label="$root.lang.control.app.create.appDesc" prop="appDesc">
          <el-input type="textarea" v-model="form.appDesc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="dialog-btn" :loading="loading" type="primary" @click="onSubmit('form')">{{ $root.lang.control.app.create.confirm }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import '@/options/baseState'
export default {
  data() {
    return {
      init: false,
      loading: false,
      fileList: [],
      ena: '',
      enb: '',
      enc: '',
      showDialog: this.show,
      editData: this.detail,
      headers: {
        Authorization: this.$store.getters.status
      },
      form: {
        appName: '',
        appVersion: '',
        appIdentification: '',
        appV: '',
        appSupplier: '',
        appMainClass: '',
        appUrl: '',
        appDesc: '',
        deviceType: '',
        isPublic: 0,
        showUrl: '',
      },
      rules: {
        appName: [{ required: true, message: this.$root.lang.control.app.create.rule.appName, trigger: 'blur' }],
        appVersion: [{ required: true, message: this.$root.lang.control.app.create.rule.appVersion, trigger: 'blur' }],
        appUrl: [{ required: true, message: this.$root.lang.control.app.create.rule.appUrl, trigger: 'blur' }],
        deviceType: [{ required: true, message: this.$root.lang.control.app.create.rule.deviceType, trigger: 'blur' }],
        isPublic: [{ required: true, message: this.$root.lang.control.app.create.rule.isPublic, trigger: 'blur' }],
        appDesc: [{ required: false, message: '', trigger: 'blur' }],
      },
      baseState: {},
      deviceTypeList: []
    }
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default: null
    }
  },
  watch: {
    show: function (value) {
      if(this.$refs['form']) this.$refs['form'].resetFields()
      if(this.$refs['appUrl']) this.$refs['appUrl'].clearFiles()
      this.form.showUrl = ''
      this.showDialog = value
      this.deviceTypeList = this.$parent.deviceTypeList
    },
    detail: function (value) {
      this.form = value
    }
  },
  computed: {
    setTitle() {
      return (this.form.id) ?  this.$root.lang.control.app.create.editTitle : this.$root.lang.control.app.create.title
    }
  },
  methods: {
    closeDialog() {
      this.$emit('editReceive',{
        key: 'showEdit',
        value: this.showDialog
      })
    },
    handleRemove(file, fileList) {
      this.form.appUrl = ''
      this.form.showUrl = ''
    },
    handlePreview(file) {
    },
    changeFile(value) {
        this.$refs[value].clearFiles()
    },
    checkLang() {
      let langType = this.$root.getStorage('lang')
      if(langType == 'en') {
        this.ena = 'Currently, one file is restricted. This time, '
        this.enb = ' files are selected. A total of '
        this.enc = ' files are selected '
        this.baseState = enBaseState
      } else {
        this.ena = '当前限制选择 1 个文件，本次选择了'
        this.enb = '个文件，共选择了'
        this.enc = '个文件'
        this.baseState = baseState
      }
    },
    onsuccess(file, fileList) {
      if(file.errorNumber == 0) {
        this.form.appUrl = file.result.url
        this.form.showUrl = fileList.name
        this.form.appIdentification = file.result.appIdentification
        this.form.appV = file.result.appV
        this.form.appSupplier = file.result.appSupplier
        this.form.appMainClass = file.result.appMainClass
        this.$refs['fileInput'].focus()
      } else {
        this.$message({
          message: file.errorMessage,
          type: 'error',
          duration: 3 * 1000
        })
      }
      
    },
    handleExceed(files, fileList) {
      this.$message.warning(`${this.ena}${files.length}${this.enb}${files.length + fileList.length}${this.enc}`);
    },
    beforeRemove(file, fileList) {
      return true
      // return this.$confirm(`${this.$root.lang.control.app.create.cDelete} ${ file.name }？`);
    },
    beforeUpload(file) {
      var type = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = type === "jar";
      if (!extension ) {
        this.$message({
          message: this.$root.lang.control.app.create.uploadTip,
          type: 'error',
          duration: 3 * 1000
        });
      }
      return extension;
    },
    onSubmit(formName) {
      let base = this
      var flag = true

      base.$refs[formName].validate((valid) => {
        if (!valid) {
          flag = false
          return false
        }
      })
      if(flag) {
        delete base.form['showUrl']
        base.doCreate()
      }
    },
    doCreate() {
      let base = this
      base.loading = true

      base.request({
        url: '/application/private/insert',
        method: 'post',
        data: base.$root.optionProcess(base.form)
      }).then(response => {
        base.loading = false
        base.showDialog = false
        base.$emit('reload')
        base.$message({
          message: this.$root.lang.confirm.addSuccess,
          type: 'success',
          duration: 3 * 1000,
        })
      }).catch(error => {
        base.loading = false
        base.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
  },
  created() {
    var lett = this;
    document.onkeydown = function(e) {
      var key = window.event.keyCode;
      var button = document.querySelector('.dialog-btn')
      if(!button) return
      if (key == 13) {
        lett.onSubmit('form')
      }
    }
    this.checkLang()
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

</style>